<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'order:flow:fh:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="90%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="pr-1 m-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <Tabs v-model:activeKey="activeKey" tabPosition="left" @tabClick="tabsClick">
      <Tabs.TabPane
        v-for="(item, index) in formTabs"
        :key="index"
        :forceRender="true"
        :tab="item.tabName"
      >
        <SingleForm
          v-if="flag && !item.tabAddress"
          :schemas="item.colList"
          :formConfig="formConfig"
          :data="record"
          ref="singleFormArr"
          :selectType="selectType"
        />
      </Tabs.TabPane>
    </Tabs>
    <template #appendFooter>
      <a-button :loading="loading" v-if="record.fhStatus != '4'" @click="handleSp()">
        <Icon icon="simple-line-icons:docs" /> {{ t('保存并审核') }}
      </a-button>
    </template>
  </BasicDrawer>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsTestTestDataForm',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import { Tabs } from 'ant-design-vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { formSet } from '/@/api/layout/layout';

  import {
    M8OrderFlowFh,
    m8OrderFlowFhSave,
    m8OrderFlowFhForm,
  } from '/@/api/m8/order/flow/fh/m8OrderFlowFh';

  import SingleForm from './singleForm.vue';

  const emit = defineEmits(['success', 'register', 'successPrint']);

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  const record = ref<M8OrderFlowFh>({} as M8OrderFlowFh);
  const getTitle = computed(() => ({
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增数据') : t('编辑数据'),
  }));
  const singleFormArr = ref<any>(null);
  let formTabs = ref<any>([]);
  let formConfig = ref<any>({});

  let selectType = ref<string>();

  let flag = ref(false);
  let loading = ref(false);

  const activeKey = ref<number>(0);

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    flag.value = false;
    activeKey.value = 0;
    loading.value = true;
    setDrawerProps({ loading: true });
    let res = await m8OrderFlowFhForm(data);

    record.value = (res.m8OrderFlowFh || {}) as M8OrderFlowFh;
    setDrawerProps({ showOkBtn: record.value.allowEdit });
    record.value.__t = new Date().getTime();
    //根据红蓝字加载表单
    let viewCode = record.value.bred === '0' ? 'M8_flow_fh_form' : 'M8_flow_fh_red_form';
    selectType.value = record.value.bred === '0' ? 'flowSelect' : 'fhSelect';

    const res11 = await formSet({ viewCode });
    formTabs.value = res11.layVoucherView.formTabs;
    formConfig.value = res11.layVoucherView.formConfig;
    flag.value = true;
    loading.value = false;
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    let obj = {} as M8OrderFlowFh;
    let falg = false;
    await singleFormArr.value.forEach((item) => {
      item.validateForm().then((e) => {
        if (!e) {
          falg = true;
        } else {
          obj = { ...obj, ...e };
        }
      });
    });

    setTimeout(async () => {
      if (falg) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      } else {
        try {
          loading.value = true;
          setDrawerProps({ confirmLoading: true });
          const params: any = {
            isNewRecord: record.value.isNewRecord,
            id: record.value.id,
          };
          const res = await m8OrderFlowFhSave(params, obj);
          showMessage(res.message);
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
          setTimeout(closeDrawer);
          emit('success', obj);
        } catch (error: any) {
          // if (error && error.errorFields) {
          //   showMessage('您填写的信息有误，请根据提示修正。');
          // }
          console.log('error', error);
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }
    }, 0);
  }
  async function handleSp() {
    let obj = {} as M8OrderFlowFh;
    let falg = false;
    await singleFormArr.value.forEach((item) => {
      item.validateForm().then((e) => {
        if (!e) {
          falg = true;
        } else {
          obj = { ...obj, ...e };
        }
      });
    });

    setTimeout(async () => {
      if (falg) {
        showMessage(t('您填写的信息有误，请根据提示修正。'));
      } else {
        try {
          loading.value = true;
          setDrawerProps({ confirmLoading: true });
          const params: any = {
            isNewRecord: record.value.isNewRecord,
            id: record.value.id,
            ope: '4',
          };
          obj.ope = '4';
          const res = await m8OrderFlowFhSave(params, obj);
          showMessage(res.message);
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
          setTimeout(closeDrawer);
          emit('successPrint', res.data);
        } catch (error: any) {
          // if (error && error.errorFields) {
          //   showMessage('您填写的信息有误，请根据提示修正。');
          // }
          console.log('error', error);
        } finally {
          loading.value = false;
          setDrawerProps({ confirmLoading: false });
        }
      }
    }, 0);
  }
</script>
